<!--
 * @Descripttion: 订单管理
 * @Author: xiao li
 * @Date: 2020-07-06 12:17:07
 * @LastEditors: xiao li
 * @LastEditTime: 2022-01-25 11:47:45
-->
<template>
  <div class="lb-order-manage">
    <top-nav />
    <div class="page-main">
      <el-row class="page-top-operate">
        <lb-button type="primary" @click="refreshOrder"
          >按分公司 / 部门更新订单</lb-button
        >
      </el-row>
      <el-row class="page-search-form">
        <el-form
          @submit.native.prevent
          :inline="true"
          :model="searchForm"
          ref="searchForm"
        >
          <el-form-item label="商品名" prop="name">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入商品名"
            ></el-input>
          </el-form-item>
          <el-form-item label="系统订单号" prop="order_code">
            <el-input
              v-model="searchForm.order_code"
              placeholder="请输入系统订单号"
            ></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input
              v-model="searchForm.phone"
              placeholder="请输入下单时输入的手机号"
              style="width: 200px"
            ></el-input>
          </el-form-item>
          <el-form-item label="状态" prop="order_status">
            <el-select
              @change="getTableDataList(1)"
              v-model="searchForm.order_status"
              placeholder="请选择"
            >
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="日期" prop="start_time">
            <el-date-picker
              @change="getTableDataList(1)"
              v-model="range"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="公司/部门" prop="company">
            <el-cascader
              @change="getTableDataList(1)"
              v-model="companyArr"
              :options="companyOptions"
              :props="{ checkStrictly: true, value: 'id', label: 'name' }"
              clearable
            ></el-cascader>
          </el-form-item>

          <el-form-item label="配送方式" prop="is_self">
            <el-select
              @change="getTableDataList(1)"
              v-model="searchForm.is_self"
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="item in sendOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <lb-button
              size="medium"
              type="primary"
              icon="el-icon-search"
              style="margin-right: 5px"
              @click="getTableDataList(1)"
              >{{ $t('action.search') }}</lb-button
            >
            <lb-button
              size="medium"
              icon="el-icon-refresh-left"
              style="margin-right: 5px"
              @click="resetForm('searchForm')"
              >{{ $t('action.reset') }}</lb-button
            >
          </el-form-item>
        </el-form>
      </el-row>
      <el-row class="page-top-operate">
        <lb-button
          size="mini"
          plain
          type="primary"
          icon="el-icon-printer"
          @click="printTable"
          >打印</lb-button
        >
        <lb-button
          size="mini"
          plain
          type="primary"
          icon="el-icon-download"
          :loading="downloadLoading"
          @click="exportOrder"
          >导出</lb-button
        >
        <!-- <el-dropdown>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>导出到Csv文件</el-dropdown-item>
                <el-dropdown-item>导出到Excel文件</el-dropdown-item>
              </el-dropdown-menu>
        </el-dropdown>-->
      </el-row>
      <el-table
        v-loading="loading"
        :data="tableData"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        style="width: 100%"
      >
        <el-table-column
          prop="id"
          label="ID"
          width="80"
          sortable
        ></el-table-column>
        <el-table-column prop="goods_info_text" width="300" label="商品信息">
          <template slot-scope="scope">
            <div
              class="table-goods-info"
              v-for="(item, index) in scope.row.goods_text"
              :key="index"
            >
              <lb-image :src="item.cover" />
              <div class="goods-info-r">
                <p>{{ item.name }}</p>
                <p>
                  <span class="price"
                    >￥{{ (item.price / item.number).toFixed(2) }}</span
                  >
                  <!-- <span class="price" v-if="item.is_sale_goods">批发价：￥{{(item.sale_price/item.number).toFixed(2)}}</span> -->
                  <span class="count">x {{ item.number }}</span>
                </p>
                <p>规格：{{ item.content }}</p>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="nickname_text"
          label="客户昵称"
        ></el-table-column>
        <el-table-column prop="staff_text" label="员工"></el-table-column>
        <el-table-column width="150" label="公司/部门">
          <template slot-scope="scope">
            <div>
              {{ scope.row.company_text.companyName }}
              <span v-if="scope.row.company_text.departmentName"
                >({{ scope.row.company_text.departmentName }})</span
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="total_price" label="实收金额"></el-table-column>
        <el-table-column
          prop="phone"
          width="120"
          label="手机号"
        ></el-table-column>
        <el-table-column prop="phone" label="支付方式">
          <template slot-scope="scope">
            <div>
              {{
                scope.row.help_pay === 1
                  ? '好友代付'
                  : scope.row.stored * 1 > 0
                  ? '储值支付'
                  : '微信支付'
              }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="out_trade_no" width="150" label="系统订单号">
          <template slot-scope="scope">
            <p>{{ scope.row.out_trade_no }}</p>
            <p>{{ scope.row.type === 1 ? '拼团' : '普通' }}</p>
          </template>
        </el-table-column>
        <el-table-column prop="transaction_id" width="150" label="商户订单号">
        </el-table-column>
        <el-table-column prop="create_time" width="120" label="下单时间">
          <template slot-scope="scope">
            <div>{{ scope.row.create_time | handleTime(1) }}</div>
            <div>{{ scope.row.create_time | handleTime(2) }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="status_text" label="状态"></el-table-column>
        <el-table-column prop="address_id" label="配送方式">
          <template slot-scope="scope">{{
            scope.row.address_id === -1 ? '自提' : '物流'
          }}</template>
        </el-table-column>
        <el-table-column prop="hx_user_text" label="核销人"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <div class="table-operate">
              <lb-button
                size="mini"
                type="primary"
                plain
                @click="$router.push('/malls/orderDetail?id=' + scope.row.id)"
                >详情</lb-button
              >
              <lb-button
                v-if="scope.row.send_status_text === 1"
                size="mini"
                type="danger"
                plain
                @click="showSendDialog(scope.row.id)"
                >发货</lb-button
              >
              <lb-button
                v-else-if="scope.row.send_status_text === 2"
                size="mini"
                type="success"
                plain
                @click="selfGoods(scope.row.id)"
                >提货</lb-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 打印表格 -->
      <table
        v-show="print"
        style="font-size: 12px"
        ref="print"
        border="0"
        cellspacing="0"
        cellapdding="0"
        class="print-table"
      >
        <thead>
          <tr>
            <th
              style="border: 1px solid"
              v-for="(item, index) in printTableData[0]"
              :key="index"
            >
              {{ item }}
            </th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in printTableData[1]" :key="index">
            <td style="border: 1px solid" v-for="(items, i) in item" :key="i">
              {{ items }}
            </td>
          </tr>
        </tbody>
      </table>
      <lb-page
        :batch="false"
        :page="searchForm.page"
        :pageSize="searchForm.limit"
        :total="total"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
      >
      </lb-page>
    </div>
    <el-dialog
      title="订单发货"
      :visible.sync="centerDialogVisible"
      width="400px"
      center
    >
      <el-form
        @submit.native.prevent
        :model="sendForm.send"
        :rules="sendFormRules"
        ref="sendForm"
        label-width="80px"
      >
        <el-form-item label="快递单号" prop="express_id">
          <el-input
            v-model="sendForm.send.express_id"
            placeholder="请输入快递单号"
          ></el-input>
        </el-form-item>
        <el-form-item label="快递公司" prop="shipper_code">
          <el-select
            v-model="sendForm.send.shipper_code"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="item in expressOptions"
              :key="item.key"
              :label="item.value"
              :value="item.key"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="快递单号" prop="courier_number">
          <el-input v-model="sendForm.courier_number" placeholder="请输入快递单号"></el-input>
        </el-form-item>
        <el-form-item label="快递公司" prop="express_company">
          <el-input v-model.number="sendForm.express_company" placeholder="请输入快递公司"></el-input>
        </el-form-item>
        <el-form-item label="查询电话" prop="express_phone">
          <el-input v-model="sendForm.express_phone" placeholder="请输入查询电话"></el-input>
        </el-form-item> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="hideSendDialog">{{ $t('action.cancel') }}</el-button>
        <el-button type="primary" @click="submitFormInfo('sendForm')">{{
          $t('action.comfirm')
        }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import pubic from '@/utils/public'
// import reg from '@/utils/reg'
export default {
  data () {
    return {
      loading: false,
      downloadLoading: false,
      centerDialogVisible: false,
      expressOptions: [{
        key: 'SF',
        value: '顺丰速运'
      },
      {
        key: 'HTKY',
        value: '百世快递'
      },
      {
        key: 'ZTO',
        value: '中通快递'
      },
      {
        key: 'STO',
        value: '申通快递'
      },
      {
        key: 'YTO',
        value: '圆通速递'
      },
      {
        key: 'YD',
        value: '韵达速递'
      },
      {
        key: 'YZPY',
        value: '邮政快递包裹'
      },
      {
        key: 'EMS',
        value: 'EMS'
      },
      {
        key: 'HHTT',
        value: '天天快递'
      },
      {
        key: 'JD',
        value: '京东快递'
      },
      {
        key: 'UC',
        value: '优速快递'
      },
      {
        key: 'DBL',
        value: '德邦快递'
      },
      {
        key: 'ZJS',
        value: '宅急送'
      },
      {
        key: 'TNT',
        value: 'TNT快递'
      },
      {
        key: 'UPS',
        value: 'UPS'
      },
      {
        key: 'DHL',
        value: 'DHL'
      },
      {
        key: 'FEDEX',
        value: 'FEDEX联邦(国内件）'
      },
      {
        key: 'FEDEX_GJ',
        value: 'FEDEX联邦(国际件）'
      }
      ],
      sendForm: {
        order_status: 2,
        id: '',
        courier_number: '',
        express_company: '',
        express_phone: '',
        send: {
          express_id: '',
          shipper_code: ''
        }
      },
      sendOptions: [
        {
          label: '第三方物流',
          value: 2
        },
        {
          label: '到店自提',
          value: 1
        }
      ],
      sendFormRules: {
        express_id: {
          required: true,
          type: 'string',
          message: '请输入快递单号',
          trigger: 'blur'
        },
        shipper_code: {
          required: true,
          type: 'string',
          message: '请选择快递公司',
          trigger: 'blur'
        }
        // courier_number: {
        //   required: true,
        //   type: 'string',
        //   message: '请输入快递单号',
        //   trigger: 'blur'
        // },
        // express_company: {
        //   required: true,
        //   type: 'string',
        //   message: '请输入快递公司',
        //   trigger: 'blur'
        // },
        // express_phone: {
        //   required: true,
        //   message: '请输入查询电话',
        //   trigger: 'blur'
        // }
      },
      print: false,
      searchForm: {
        page: 1,
        limit: 10,
        name: '',
        order_code: '',
        transaction_id: '',
        phpne: '',
        order_status: '',
        is_self: ''
      },
      companyArr: [],
      companyOptions: [
        {
          id: 0,
          name: '全部'
        }
      ],
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        }
      },
      range: '',
      statusOptions: [
        {
          label: '全部订单',
          value: 0
        },
        {
          label: '未支付',
          value: 1
        },
        {
          label: '待发货',
          value: 2
        },
        {
          label: '已发货',
          value: 3
        },
        {
          label: '已完成',
          value: 4
        },
        {
          label: '已取消/拼团超时失败',
          value: 5
        }
      ],
      tableData: [],
      printTableData: [],
      total: 0,
      multipleSelection: []
    }
  },
  created () {
    this.getTableDataList()
    this.getSelectOptions()
  },
  methods: {
    resetForm (name) {
      this.range = ''
      this.companyArr = []
      this.$refs[name].resetFields()
      this.getTableDataList(1)
    },
    handleSizeChange (val) {
      this.searchForm.limit = val
      this.handleCurrentChange(1)
    },
    handleCurrentChange (val) {
      this.searchForm.page = val
      this.getTableDataList()
    },
    /**
     * @method 按部门公司跟新
     */
    refreshOrder () {
      this.$api.getRefreshOrder().then(res => {
        console.log(res)
        if (res.code === 200) {
          this.$message.success('更新成功！')
          this.getTableDataList()
        }
      })
    },
    /**
     * @method 搜索订单列表
     */
    getTableDataList (flag) {
      if (flag) this.searchForm.page = 1
      this.loading = true
      let { searchForm, range } = this
      // alert(range)
      if (range && range.length > 0) {
        searchForm.start_time = range[0]
        searchForm.end_time = range[1]
      } else {
        searchForm.start_time = ''
        searchForm.end_time = ''
      }
      let { companyArr } = this
      searchForm.company = companyArr[companyArr.length - 1] || ''
      console.log(searchForm)
      this.$api.getGoodsOrderList(searchForm).then(res => {
        this.loading = false
        if (res.code === 200) {
          this.tableData = res.data.data
          this.total = res.data.total
          let arr = res.data.data.map(item => {
            return [
              item.id,
              item.goods_info_text,
              item.user_id,
              item.nickname_text,
              item.staff_text,
              item.company_text.companyName + item.company_text.departmentName,
              item.total_price,
              item.address_text,
              item.phone,
              item.stored * 1 > 0 ? '储值支付' : '微信支付',
              item.out_trade_no,
              item.transaction_id,
              moment(item.create_time * 1000).format('YYYY-MM-DD HH:mm:ss'),
              item.type === 1 ? '拼团' : '普通',
              item.status_text,
              item.hx_user_text
            ]
          })
          this.printTableData = [
            [
              'ID',
              '商品',
              '用户ID',
              '用户昵称',
              '员工',
              '公司/部门',
              '实收金额',
              '收货地址',
              '手机号',
              '支付方式',
              '系统订单号',
              '商户订单号',
              '下单时间',
              '类型',
              '状态',
              '核销人'
            ],
            arr
          ]
        }
      })
    },

    /**
     * @method 导出订单
     */
    exportOrder () {
      this.downloadLoading = true
      let searchForm = JSON.parse(JSON.stringify(this.searchForm))
      let range = JSON.parse(JSON.stringify(this.range))
      if (range && range.length > 0) {
        searchForm.start_time = range[0]
        searchForm.end_time = range[1]
      } else {
        searchForm.start_time = ''
        searchForm.end_time = ''
      }
      let url = pubic.getProCurrentHref()
      let keywords = url.indexOf('?') > 0 ? '' : '?'
      let flag = url.indexOf('?') > 0
      Object.getOwnPropertyNames(searchForm).forEach((keys, value) => {
        keywords += flag
          ? `&${keys}=${searchForm[keys]}`
          : `${keys}=${searchForm[keys]}`
        flag = true
      })
      let token = sessionStorage.getItem('minitk')
      let dwonlaodUrl = `${url}/shop/AdminExcel/orderExcel${keywords}&token=${token}`
      window.location.href = dwonlaodUrl
      setTimeout(() => {
        this.downloadLoading = false
      }, 5000)
    },

    /**
     * @method 发货
     */
    submitFormInfo (name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          let { sendForm } = this
          sendForm.courier_number = sendForm.send.express_id
          sendForm.express_company = this.expressOptions.filter(item => {
            return item.key === sendForm.send.shipper_code
          })[0].value
          this.$api.orderSettingSendGoods(sendForm).then(res => {
            console.log(res)
            if (res.code === 200) {
              this.$message.success(this.$t('tips.successSub'))
              this.centerDialogVisible = false
              this.getTableDataList()
            }
            this.sendForm = {
              order_status: 2,
              id: '',
              courier_number: '',
              express_company: '',
              express_phone: '',
              send: {
                express_id: '',
                shipper_code: ''
              }
            }
          })
        }
      })
    },
    /**
     * @method 打开发货弹框
     */
    showSendDialog (id) {
      this.sendForm.id = id
      this.centerDialogVisible = true
    },
    /**
     * @method 获取下拉菜单的选项值
     */
    getSelectOptions () {
      this.$api.GoodsListSelect().then(res => {
        if (res.code === 200) {
          let { companyOptions, cateOptions } = this
          let { cate, company } = res.data
          this.companyOptions = companyOptions.concat(company)
          this.cateOptions = cateOptions.concat(cate)
        }
      })
    },
    /**
     * @method 隐藏发货弹框
     */
    hideSendDialog () {
      this.centerDialogVisible = false
      this.sendForm = {
        order_status: 2,
        id: '',
        courier_number: '',
        express_company: '',
        express_phone: '',
        send: {
          express_id: '',
          shipper_code: ''
        }
      }
    },
    /**
     * @method 提货
     */
    selfGoods (id) {
      this.$confirm(this.$t('tips.confirmOperate'), this.$t('tips.reminder'), {
        confirmButtonText: this.$t('action.comfirm'),
        cancelButtonText: this.$t('action.cancel'),
        type: 'warning'
      }).then(() => {
        this.$api
          .orderSettingSelfGoods({
            id
          })
          .then(res => {
            console.log(res)
            if (res.code === 200) {
              this.$message.success(this.$t('tips.successOper'))
              this.getTableDataList()
            }
          })
      })
    },

    /**
     * @method 跳转详情
     */
    jumpToDetail () {
      this.$router.push()
    },
    /**
     * @method 打印表格
     */
    printTable () {
      this.print = true
      setTimeout(() => {
        this.$print(this.$refs.print)
        this.print = false
      }, 50)
    }
  },
  filters: {
    handleTime (val, type) {
      let time = type === 1 ? moment(val * 1000).format('YYYY-MM-DD') : type === 2 ? moment(val * 1000).format('HH:mm:ss') : moment(val * 1000).format('YYYY-MM-DD HH:mm:ss')
      return time
    }
  }
}
</script>

<style lang="scss" scoped>
.lb-order-manage {
  .page-main {
    width: 100%;
    padding: 20px;

    .el-select,
    .el-input-number,
    .el-input {
      width: 200px;
    }
    .el-table {
      .table-goods-info {
        width: 280px;
        height: 80px;
        display: flex;
        align-items: center;
        margin-bottom: 10px;
        font-size: 12px;

        .goods-info-r {
          width: 100%;
          display: flex;
          flex-direction: column;
          justify-content: space-around;

          p {
            width: 210px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .price {
            color: red;
          }
        }

        .el-image {
          min-width: 70px;
          height: 70px;
          margin-right: 10px;
        }

        &:last-child {
          margin-bottom: 0;
        }
      }
    }
    .print-table {
      position: fixed;
      bottom: -999999px;
    }
  }
}

.none {
  display: none;
}
</style>
<style media="print">
.none {
  display: block;
}
</style>
